package controller

import (
	"appService/src/application"
	"appService/src/application/admin/admin/adminModels"
	"appService/src/application/app/appModels"
	"appService/src/application/request"
	"appService/src/authValid"
	"appService/src/authValid/defaultB"
	"appService/src/authValid/userAuthType"
	"appService/src/config"
	"appService/src/orm"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"xorm.io/builder"
	"xorm.io/xorm"
)

//Branch 部门机构
type Branch struct {
	application.BaseController
}

//getModel 获取控制器对应的 模型
func  (*Branch)getModel() appModels.IModel{
	return new(adminModels.Branch)
}

//SetDefault 设置默认的部门机构
func (this *Branch) SetDefault(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	id := r.GetString("id")
	if id == "" {
		req.JsonError("请选择要设置默认的【部门机构】")
	}
	branch := new(adminModels.Branch)
	has, err := orm.Db.Where(builder.Eq{"id": id}).Get(branch)
	if err != nil {
		g.Log().Errorf("SetDefault：设置默认的部门机构，错误：%v", err)
		req.JsonError("设置失败")
	}
	if !has {
		req.JsonError("部门机构不存在")
	}
	err = orm.Transaction("设置", func(db *xorm.Session) error {
		_, err := db.Table(new(adminModels.Branch)).Where(builder.Eq{"id": branch.Id}).Update(map[string]int{"is_default": 1})
		if err != nil {
			g.Log().Errorf("设置默认的【部门机构】,错误：%v", err)
			return err
		}
		_, err = db.Table(new(adminModels.Branch)).Where(builder.Neq{"id": branch.Id}).Update(map[string]int{"is_default": 2})
		if err != nil {
			g.Log().Errorf("设置默认的【部门机构】,错误：%v", err)
			return err
		} else {
			return nil
		}
	})
	if err == nil {
		branch.IsDefault = 1
		defaultB.DefaultBranch = *branch
		req.JsonSuccess("设置成功")
	} else {
		req.JsonErrorf("%v", err)
	}
}

//UserBranchID 获取当前用户可以拥有的部门机构ID
func (this *Branch) UserBranchID(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.JsonSuccessData(req.LoginUser.BranchIds)
}
//isRoles 判断用户是否有权限赋予角色给部门机构
func (this *Branch) isRoles(req *request.Request) {
	if config.BranchAuthOpen {
		branch :=new(adminModels.Branch)
		req.ParamsAnalyse(branch)
		if req.LoginUser.Account.AccountType != userAuthType.SYSTEM_ADMIN {
			for _, v := range branch.Roles {
				for _,id:=range v.Roles{
					role := authValid.GetRole(id)
					if role == nil {
						req.JsonError("操作失败，角色不存在")
					} else {
						if role.RoleType > req.LoginUser.Account.AccountType {
							req.JsonErrorf("您没有权限赋予【%v】角色给该部门机构", role.RoleName)
						}
					}
				}
			}
		}
	}
}
//Add 添加
func (this *Branch) Add(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	this.isRoles(req)
	req.AddHandle(func() {
		branch := req.Model.(*adminModels.Branch)
		authValid.BranchSet(branch)
	})
}

//Delete 删除
func (this *Branch) Delete(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	req.DeleteHandle(func(ids []string) {
		for _, id := range ids {
			authValid.BranchRemove(id)
		}
	})
}

//Edit 修改
func (this *Branch) Edit(r *ghttp.Request) {
	req := this.NewRequest(r,this.getModel())
	this.isRoles(req)
	req.EditHandle(func() {
		branch := req.Model.(*adminModels.Branch)
		authValid.BranchSet(branch)
	})
}

//Get 获取
func (this *Branch) Get(r *ghttp.Request)  {
	this.NewRequest(r,this.getModel()).Get()
}
//List 获取
func (this *Branch) List(r *ghttp.Request)  {
	this.NewRequest(r,this.getModel()).List()
}
